package zut.edu.cn.concertticketmanagementsystem.service;

import net.bytebuddy.utility.RandomString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zut.edu.cn.concertticketmanagementsystem.Dao.TicketDao;
import zut.edu.cn.concertticketmanagementsystem.entity.Ticket;

import java.util.List;
import java.util.Random;

@Service
public class Ticketserviceimpl implements Ticketservice {

    @Autowired
    TicketDao ticketDao;
    Ticket ticket=new Ticket();

    @Override
    public List<Ticket> findAll() {

        return ticketDao.findAll();
    }

    @Override
    public List<Ticket> queryAllbysingername(String singername) {
        return ticketDao.findByT_singername(singername);
    }

    @Override
    public void deleteByT_id(int t_id) {
        ticketDao.deleteById(t_id);

    }

    @Override
    public String byticket(int t_id) {

        //票据用随机生成的字符串代替
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String tbill;
        int count = ticketDao.findById(t_id).get().getT_remaincount();
        if (count >= 1) {
            Random random = new Random();
            StringBuffer tb = new StringBuffer();
            for (int i = 0; i < 10; i++) { // 生成10位数据码
                int number = random.nextInt(62);
                tb.append(str.charAt(number));
            }
            ticketDao.findById(t_id).get().setT_remaincount(--count); //票数减一
            tbill = "购票成功! 您的票据为：" + tb.toString();
        } else
            tbill = "很遗憾,余票不足！";

        return tbill;

    }

    @Override
    public List<Ticket> queryAllbyaddress(String address) {
        return ticketDao.findAllByT_addressLike(address);
    }

    @Override
    public Ticket save(Ticket ticket) {

        return ticketDao.save(ticket);
    }

    @Override
    public Ticket findOneById(int t_id){
        return ticketDao.findAllById(t_id);
    }

    @Override
    public List<Ticket> findOnAll() {
        return ticketDao.findAllByT_type();
    }

    @Override
    public Ticket onSale(int t_id) {

        int td=ticketDao.updateonT_type(t_id);
        return ticketDao.findAllById(td);

    }

    @Override
    public Ticket offSale(int t_id) {
        int td=ticketDao.updateoffT_type(t_id);
        return ticketDao.findAllById(td);
    }

    @Override
    public void increaseStock(int t_id,int icount) {
        Ticket ticket=ticketDao.findAllById(t_id);
        ticket.setT_count(ticket.getT_count()+icount);
        ticket.setT_remaincount(ticket.getT_remaincount()+icount);
        ticketDao.save(ticket);
    }


    @Override
    public void decreaseStock(int t_id,int dcount) {
        Ticket ticket=ticketDao.findAllById(t_id);
        ticket.setT_count(ticket.getT_count()-dcount);
        ticket.setT_remaincount(ticket.getT_remaincount()-dcount);
        ticketDao.save(ticket);
    }
}
